import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import React, { useEffect, useRef, useState } from 'react';
import { promoteProducts, saveFlowOrders  } from './service';
import type { ChannelRequest } from './data';
import moment from 'moment';
import { useModel } from '@umijs/max';
import { fetchChannelUser, getStoreCate } from '../DyCps/service';
import { message } from 'antd';
import FollowOrderForm from './components/FollowOrderForm';
const commandStatus = {
  1: {
    text: '使用中',
    status: 'Success',
  },
  0: {
    text: '已下线',
    status: 'Error',
  },
  2: {
    text: '已失效',
    status: 'Error',
  }
};
const handleUpdateOrders = async (selectedRows: any) => {
  const hide = message.loading('正在更新');
  try {
    const rsp = await saveFlowOrders({ ...selectedRows });
    if(rsp.data.upType === "view") {
      if(rsp.data.url === "true") {
        message.success('跟单成功');
      } else {
        message.error('跟单失败');
      }
    } else{
      window.open(rsp.data.url);
    }
    // 
    hide();
    
    return true;
  } catch (error) {
    hide();
    message.error('跟单失败');
    return false;
  }
};

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>(null);
  const [dateRange, setDateRange] = useState<any>();
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const [requestStatus] = useState(currentUser?.userInfo?.role==='normal')
  const [updateOrdersVisible, handleUpdateOrdersVisible] = useState(false);
  const [currentProductRow, setCurrentProductRow] = useState<any>({});

  const columns: ProColumns<API.RuleListItem>[] = [
   
    {
      title: '项目名称',
      dataIndex: 'name',
      width:100,
      // copyable: true,
      hideInSearch: true
    },
    // {
    //   title: '店铺信息',
    //   dataIndex: 'shopName',
    //   copyable: true,
    //   width: 100,
    // },
    {
      title: '产品名称',
      dataIndex: 'productName',
      width:80,
      copyable: true,
      // hideInSearch: true
    },
    {
      title: '产品分类',
      dataIndex: 'cate',
      valueType: "select",
      width:50,
      request: async ()=>{
        const rsp = await getStoreCate();
        return rsp.data;
      }
    },
    {
      title: '渠道',
      dataIndex: 'channelId',
      hideInTable: requestStatus,
      hideInSearch: requestStatus,
      valueType: "select",
      request: async ()=>{
        const rsp = await fetchChannelUser({});
        return rsp.data;
      }
    },
    {
      title: '今日订单数',
      dataIndex: 'dayOrder',
      hideInSearch: true,
      hideInTable: requestStatus
    },
    {
      title: '佣金比例',
      dataIndex: 'rate',
      width: 80,
      hideInSearch: true,
      sorter: (a, b) => a.rate - b.rate,
      renderText(text) {
          return text + '%'
      },
    },
    {
      title: '微信口令',
      dataIndex: 'wxCommand',
      hideInSearch: true,
      copyable: true,
      render:(text,record)=>{
        if(record.status !== 1) {
          return null;
        } else{
          return text;
        }
      }
    },
    {
      title: '口令状态',
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: commandStatus
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      width: 100,
      valueType: 'dateTime'
      
    },
    {
      title: '口令开始时间',
      dataIndex: 'startTime',
      hideInSearch: true,
      width: 100,
      valueType: 'dateTime'
    },
    {
      title: '口令失效时间',
      dataIndex: 'endTime',
      hideInSearch: true,
      width: 100,
      valueType: 'dateTime'
    },
    {
      title: '项目创建时间',
      dataIndex: 'orderDate',
      valueType: 'dateRange',
      hideInForm: true,
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
        fieldProps: {
          value: dateRange,
          onChange: (value:any) => {
            if (value && value.length === 2) {
              setDateRange(value);
            }
          },
        },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 80,
      align: 'right',
      render: (text, record) =>{  
        return  [
        
          currentUser?.userInfo?.role==='normal' ? 
          <a
            key="follow"
            onClick={async () => {
              handleUpdateOrdersVisible(true);
              setCurrentProductRow(record);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }}
          >
            跟单
          </a> :''
        ]
      },
    },
  ];
  useEffect(() => {
    const startOfDay = new Date(new Date());
    startOfDay.setHours(0, 0, 0, 0);
    startOfDay.setDate(startOfDay.getDate() - 3);
    const endOfDay = new Date(new Date).setHours(23,59,59,0);
    setDateRange([startOfDay, endOfDay]);
  }, []);

  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={'全部口令'}
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: "1100px" }}
      
        request={async (params: ChannelRequest) => {
          const defaultValues = columns.reduce((acc:any, column:any) => {
            if (column.fieldProps && column.fieldProps.value !== undefined) {
              acc[column.dataIndex] = column.fieldProps.value;
            }
            return acc;
          }, {});
          const currentDate = moment(new Date(dateRange[0]));
          const startTime = currentDate.subtract(3, 'days').format('YYYY-MM-DD HH:mm:ss');
          console.log(startTime)
          const endTime = moment(new Date(dateRange[1]).setHours(23,59,59,0)).format('YYYY-MM-DD HH:mm:ss');

          // 将默认值合并到请求参数中
          const data = { ...params, ...defaultValues, startTime, endTime };

          const rsp = await promoteProducts(data);
          if (rsp.code === 'SUCCESS') {
            return {
              data: rsp.data.data,
              total: rsp.data.total,
            };
          }
        }}
        search={{
          labelWidth: 100,
          defaultCollapsed: false, // 默认展开搜索栏
        }}
        pagination={
          {
            pageSize: 20
          }
        }
        columns={columns}
      />
      <FollowOrderForm
        onSubmit={async (value) => {
          // console.log(value);
          // return;
          const success = await handleUpdateOrders({ ...value });
          if (success) {
            handleUpdateOrdersVisible(false);
            setCurrentProductRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onUpdate={async (value) => {
          handleUpdateOrdersVisible(false);
          setCurrentProductRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
          window.open(value)
        }}
        onCancel={() => {
          handleUpdateOrdersVisible(false);
          setCurrentProductRow(undefined);
        }}
        updateModalVisible={updateOrdersVisible}
        values={currentProductRow || {}}
        formType={0}
      />
    </PageContainer>
  );
};
export default TableList;
